package cn.rxmind.dlicense.core.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 部署机器信息获取工具
 *
 * @author renxin
 * @email renxinzhiliangzhi@163.com
 * @date 2021/4/15 3:55 下午
 */
public class MachineInfoUtil {

    private MachineInfoUtil() {
    }

    /**
     * IP 地址获取
     *
     * @return
     * @throws Exception
     */
    public static Set<String> getIpAddress() {

        return getLocalAllInetAddress().stream().map(ip -> ip.getHostAddress().toLowerCase()).collect(Collectors.toSet());
    }

    /**
     * MAC 地址获取
     * @return
     */
    public static Set<String> getMacAddress() {

        return getLocalAllInetAddress().stream().map(MachineInfoUtil::getMacByInetAddress).collect(Collectors.toSet());
    }

    private static List<InetAddress> getLocalAllInetAddress() {

        List<InetAddress> result = new ArrayList<>(4);
        Enumeration<NetworkInterface> interfaceEnumeration = null;
        try {
            interfaceEnumeration = NetworkInterface.getNetworkInterfaces();
        }catch (Exception e){
            System.err.printf("获取当前机器IP地址发生错误%s%n",e.getMessage());
            return new ArrayList<>();
        }
        while(interfaceEnumeration.hasMoreElements()){
            // 取出网卡接口
            NetworkInterface iface = interfaceEnumeration.nextElement();
            // 取出网卡接口下的IP
            Enumeration<InetAddress> inetAddressEnumeration = iface.getInetAddresses();
            while(inetAddressEnumeration.hasMoreElements()){
                InetAddress inetAddr = inetAddressEnumeration.nextElement();

                //排除LoopbackAddress、SiteLocalAddress、LinkLocalAddress、MulticastAddress类型的IP地址
                if(!inetAddr.isLoopbackAddress()
                        && !inetAddr.isLinkLocalAddress()
                        && !inetAddr.isMulticastAddress()){
                    result.add(inetAddr);
                }
            }
        }

        return result;
    }

    /**
     * 获取mac
     *
     * @param inetAddr
     * @return
     */
    private static String getMacByInetAddress(InetAddress inetAddr) {

        byte[] mac = null;
        try {
            NetworkInterface.getByInetAddress(inetAddr).getHardwareAddress();
        }catch (Exception e){
            System.err.printf("获取当前机器Mac地址发生错误！%s%n",e.getMessage());
            return "ERROR";
        }

        StringBuilder stringBuilder = new StringBuilder();

        for(int i=0;i<mac.length;i++){
            if(i != 0) {
                stringBuilder.append("-");
            }

            //将十六进制byte转化为字符串
            String temp = Integer.toHexString(mac[i] & 0xff);
            if(temp.length() == 1){
                stringBuilder.append("0").append(temp);
            }else{
                stringBuilder.append(temp);
            }
        }

        return stringBuilder.toString().toUpperCase();

    }


}
